package com.tebiecloud.base.server.service.impl;

import com.tebiecloud.base.client.model.entity.BaseApp;
import com.tebiecloud.base.server.mapper.BaseAppMapper;
import com.tebiecloud.base.server.service.BaseAppService;
import com.tebiecloud.base.server.service.BaseAuthorityService;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.tebiecloud.common.security.SecurityClientDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统应用-基础信息 服务实现类
 * @author tebie
 * @date 2019-08-01
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BaseAppServiceImpl extends BaseServiceImpl<BaseAppMapper, BaseApp> implements BaseAppService {

    @Autowired
    private BaseAuthorityService baseAuthorityService;

    @Autowired
    private JdbcClientDetailsService jdbcClientDetailsService;

    /**
     * 获取app和应用信息
     * @param clientId
     * @return
     */
    @Override
    @Cacheable(value = "apps", key = "'client:' + #clientId")
    public SecurityClientDetails getClientDetails(String clientId) {
        BaseClientDetails baseClientDetails = (BaseClientDetails) jdbcClientDetailsService.loadClientByClientId(clientId);
        if (baseClientDetails == null) {
            return null;
        }
        String appId = baseClientDetails.getAdditionalInformation().get("appId").toString();
        SecurityClientDetails openClient = new SecurityClientDetails();
        BeanUtils.copyProperties(baseClientDetails, openClient);
        openClient.setAuthorities(baseAuthorityService.getSecurityAuthorityListByAppId(appId));
        return openClient;
    }

}
